(function () {
    var LayUITreeGrid = function (tableId, url, columns) {
        this.tableId = tableId;
        this.url = url;
        this.method = "post";
        this.idField = "code";
        this.isFilter = false;
        this.iconOpen = false;
        this.treeId = "code";//树形id字段名称
        this.treeUpId = "pcode"; //树形父id字段名称
        this.treeShowName = "name"; //以树形式显示的字段
        this.columns = columns;
        this.queryParams = null; // 向后台传递的自定义参数
        this.table = null;
        this.tableRender = null;
        this.page = false;
        this.skin = '';
        this.params = {};
        /**
         * 默认排序
         * @type {{
                    field: 'id' //排序字段，对应 cols 设定的各字段名
                    ,type: 'desc' //排序方式  asc: 升序、desc: 降序、null: 默认排序
                  }
         *}
         */
        this.defaultSort = null;
        this.openToolBar = true;
        this.handleListenToolBar = null;
        this.handleListenTool = null;
        this.handleListenCheckbox = null;
    };

    LayUITreeGrid.prototype = {
        /**
         * 初始化 table
         */
        init: function () {
            var tableId = this.tableId;
            var me = this;
            if (typeof this.queryParams == 'function') {
                this.data = this.queryParams();
            }
            me.table = layui.treeGrid;
            me.table.init();
            //第一个实例
            var p = {
                id: tableId,
                elem: '#' + tableId,
                url: Dawn.api + me.url
                , idField: me.idField
                , iconOpen: me.iconOpen
                , treeId: me.treeId
                , treeUpId: me.treeUpId
                , treeShowName: me.treeShowName
                ,
                method: me.method,
                where: me.data,
                done: function () {
                },
                page: this.page,
                skin: me.skin,
                cols: me.columns,
                contentType: 'application/json',
                loading: true,
                headers: {
                    Authorization: $.cookie("Authorization")
                }
                ,parseData: function(res){
                    if (res.code === -3) {
                        $.removeCookie("Authorization");
                        localStorage.removeItem("Authorization");
                        localStorage.removeItem("account");
                        window.location.href = Dawn.ctxPath + "/login.html";
                    }
                    if (res.code !== 0) {
                        Dawn.error(res.message);
                    }
                    return res;
                }
            };
            if (this.openToolBar) {
                p.toolbar = '#' + tableId + 'ToolBar';
            }
            if (typeof this.params == 'object') {
                for (var name in this.params) {
                    p[name] = this.params[name];
                }
            }
            me.tableRender = me.table.render(p);
            if (me.defaultSort != null) {
                me.table.reload(tableId, {
                    initSort: me.defaultSort //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                    , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        field: me.defaultSort.field //排序字段
                        , order: me.defaultSort.type //排序方式
                    }
                });
            }
            //添加排序监听
            me.table.on('sort(' + tableId + ')', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                me.table.reload(tableId, {
                    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
                    , where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                        field: obj.field //排序字段
                        , order: obj.type //排序方式
                    }
                });
            });
            this.renderToolBar();
            me.listenTool(function (event, data, obj) {
                if (typeof me.handleListenTool == 'function') {
                    me.handleListenTool(event, data, obj);
                }
            });
            me.listenCheckbox(function (checked, obj) {
                if (typeof me.handleListenCheckbox == 'function') {
                    me.handleListenCheckbox(checked, obj)
                }
            });
            return this;
        },
        /**
         * 导出数据
         */
        exportFile: function (type) {
            this.table.exportFile(this.tableRender.config.id, type);
        },
        /**
         * 向后台传递的自定义参数
         * @param param
         */
        setQueryParams: function (param) {
            this.queryParams = param;
        },
        /**
         * 获取表
         * @returns {*}
         */
        getTable: function () {
            return this.table;
        },
        /**
         * 设置ajax post请求时候附带的参数
         */
        set: function (key, value) {
            if (typeof key == "object") {
                for (var i in key) {
                    if (typeof i == "function")
                        continue;
                    this.data[i] = key[i];
                }
            } else {
                this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
            }
            return this;
        },

        /**
         * 设置ajax post请求时候附带的参数
         */
        setData: function (data) {
            this.data = data;
            return this;
        },

        /**
         * 清空ajax post请求参数
         */
        clear: function () {
            this.data = {};
            return this;
        },

        refresh: function () {
            this.table.reload(this.tableId, {where: this.queryParams()});
            this.renderToolBar();
        },
        renderToolBar: function () {
            let me = this;
            me.listenToolBar(function (event, checkStatus, obj) {
                if (event == 'LAYTABLE_FLUSH') {
                    me.refresh();
                }
                if (typeof me.handleListenToolBar == 'function') {
                    me.handleListenToolBar(event, checkStatus, obj);
                }
            });
        },
        /**
         * 监听表格中按钮
         * event lay-event
         * data  按钮所在行的数据
         * @param {Object} handle
         */
        listenTool: function (handle) {
            //监听行工具事件
            this.table.on('tool(' + this.tableId + ')', function (obj) {
                if (typeof (handle) == 'function')
                    handle(obj.event, obj.data, obj);
            });
        },
        /**
         * 监听工具栏
         * event lay-event
         * checkStatus  选中的数据
         * @param {Object} handle
         */
        listenToolBar: function (handle) {
            var me = this;
            $("." + this.tableId + " .layui-table-tool *[lay-event]").unbind();
            $("." + this.tableId + " .layui-table-tool *[lay-event]").click(function (){
                if (typeof (handle) == 'function') {
                    var checkStatus = me.table.checkStatus(me.tableId);
                    handle($(this).attr("lay-event"), checkStatus, $(this));
                }
            });
        },
        /**
         * 监听复选框选择
         * @param {Object} handle
         */
        listenCheckbox: function (filter, handle) {
            var form = layui.form;
            form.on('checkbox(' + filter + ')', function (obj) {
                if (typeof (handle) == 'function') {
                    handle(obj.elem.checked, obj);
                }
            });

        }
    };

    window.LayUITreeGrid = LayUITreeGrid;

}());
